/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.file.resource;

import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ibm.iisp.common.file.util.FileStoreUtils;

/**
 * 
 * 用于通过REST接口上传文件
 * 
 */
@RestController
@RequestMapping()
public class FileUploadResource {
	/**
	 * 
	 */
	private static final String TMP_UPLOAD_FOLDER = FileStoreUtils.TEMP_PATH + "/upload/";
	Logger log = LoggerFactory.getLogger(getClass());
	@Inject
	FileStoreUtils fileStoreUtils;

	@PostMapping("/common/files")
	public Map<String, ?> upLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String upload_file_path = fileStoreUtils.getAbsFilePath(TMP_UPLOAD_FOLDER);
		// 设置工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置文件存储位置
		factory.setRepository(Paths.get(upload_file_path).toFile());
		// 设置大小，如果文件小于设置大小的话，放入内存中，如果大于的话则放入磁盘中,单位是byte
		factory.setSizeThreshold(1024 * 1024);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// 这里就是中文文件名处理的代码，其实只有一行
		upload.setHeaderEncoding("utf-8");
		String fileName = null;
		HashMap<String, Object> map = new HashMap<>();
		ArrayList<String> filePaths = new ArrayList<>();
		List<FileItem> list = upload.parseRequest(request);
		for (FileItem item : list) {
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString("utf-8");
				log.info("Received request parameter: {} = {};", name, value);
			} else {
				String name = item.getFieldName();
				String value = item.getName();
				log.info("Received file field:{}, name:{};", name, value);
				fileName = Paths.get(value).getFileName().toString();
				request.setAttribute(name, fileName);
				if (!Paths.get(upload_file_path).toFile().exists()) {
					Paths.get(upload_file_path).toFile().mkdirs();
				}
				// 写文件到upload目录，文件名filename
				String fn = upload_file_path + fileName;
				item.write(new File(upload_file_path, fileName));
				filePaths.add(fn);
			}
		}
		map.put("status", 200);
		map.put("uploadPaths", filePaths);
		return map;
	}

}